<?php
/**
 * 索真api接口
 */
namespace bc\api;

use bc\util\Util;
use bc\model\api\ApiLogModel;
use bc\util\Sms;

class SzApi
{
	
	/**
	 * 
	 * @var string
	 */
	const KEY = 'iMtTt7jTgps+FV+2sQWJqpkWHLncA9H7q4nBvO54Yrk';
	
	/**
	 * 
	 * @var string
	 */
	//测试环境地址
 	const URL = 'http://pubtest.api.thorgene.com/pub-gene-api/';
	//正式环境地址
	//const URL = 'http://thorgene.com/pub-gene-api/';
	
	/**
	 * 
	 * @var unknown
	 */
	const CALLER = 'zhishimama';
	
	
	/**
	 * 
	 * @param $randValue
	 */
	public function getSign($randValue = null)
	{
		if(is_null($randValue))
		{
			$randomStr = rand ( 1, 999 );
		}
		else
		{
			$randomStr = $randValue;
		}
		$sign = md5 ( self::KEY  . $randomStr );
		return ['sign' => $sign, 'random_str' => $randomStr];
	}
	
	
	/**
	 * 获取采样管信息
	 * @param string $sampleNo
	 * @throws \Exception
	 */
	public function searchInfo($sampleNo)
	{
		if(!$sampleNo)
			throw new \Exception('sampleNo not empty!');
		
		$arrSign = $this->getSign();
			
		$params['sampleNo'] = $sampleNo;
		$params['caller'] = self::CALLER;
		$params['randomStr'] = $arrSign['random_str'];
		$params['sign'] = $arrSign['sign'];
		$result = Util::httpGet(self::URL . 'sample', $params);
		
		
		$data['api_type'] = 1;
		$data['request_params'] = json_encode($params);
		$data['status'] = 1;
		$data['result_params'] = $result;
		
		$result_arr = json_decode($result, true);
		//返回接口有错误 调用短信提醒
		if($result_arr['retCode'] != 0)
		{
			$data['status'] = 0;
			$sms = new Sms();
			$sms->setMobile('18721271173');
			$sms->setText(date('Y-m-d H:i:s') . '索真-获取采样管信息出错');
			$sms->send();
		}
		
		$apiModel = new ApiLogModel();
		$apiModel->add($data);
		
		return $result;
	}
	
	/**
	 * 录入检测人信息
	 * @param array $params
	 *  $params ['sampleNo'] = '1038630000604';
	 *	$params ['name'] = 'gray';
	 *	$params ['sex'] = 0;  					检测人性别，0表示男，1表示女
	 *	$params ['birthday'] = '1987-12-18';  	检测人出生日期，格式如1970-05-02
	 *
	 * @return json
	 */
	public function SampleChecker(array $params)
	{
		$arrSign = $this->getSign();
		$url = self::URL . 'sample-checker?caller=' .  self::CALLER  . '&randomStr=' . $arrSign ['random_str'] . '&sign=' . $arrSign ['sign'];
		$json = Util::jsonEncode( $params );
		
		$result = Util::jsonPost($url, $json);
		
		$data['api_type'] = 2;
		$data['request_params'] = $json;
		$data['status'] = 1;
		$data['result_params'] = $result;
		
		$result_arr = json_decode($result, true);
		//返回接口有错误 调用短信提醒
		if($result_arr['retCode'] != 0)
		{
			$data['status'] = 0;
			$sms = new Sms();
			$sms->setMobile('18721271173');
			$sms->setText(date('Y-m-d H:i:s') . '索真-录入检测人信息出错');
			$sms->send();
		}
		
		$apiModel = new ApiLogModel();
		$apiModel->add($data);

		return $result;
	}
	
}

